<script setup>

import BaseIcon from "@/components/Icon/BaseIcon.vue";
import {reactive, ref} from "vue";
import {getDeepSeekResponse,getLegalAdvice} from "@/api/ai/index.js";

const inputMesg = ref('');
const isLoading = ref(false);

const messages = reactive([{
  text: '您好！我是法律AI助手，请提出您关心的法律问题',
  sender: 'system',
  timestamp: new Date()
},{
  text: '我想咨询一下法律问题',
  sender: 'user',
  timestamp: new Date()
}
]);

const sendMsg = () => {
  messages.push({
    text: inputMesg.value,
    sender: 'user',
    timestamp: new Date()
  })
  inputMesg.value = ''
  isLoading.value = true;

  // // 准备消息历史 (只保留最近的4条)
  const recentHistory = messages
      .slice(-4)
      .filter(msg => msg.sender !== 'system') // 排除系统消息
      .map(msg => ({
        role: msg.sender === 'user' ? 'user' : 'assistant',
        content: msg.text
      }));

   getLegalAdvice(inputMesg.value, recentHistory).then(res=>{
     messages.push({
       text: res,
       sender: 'system',
       timestamp: new Date()
     })
     isLoading.value = false;
  })
}

function formatBotMessage(text) {
  // 查找并高亮法律条文引用
  const lawRegex = /《([^》]+)》第([\d零一二三四五六七八九十百千]+)条/g;
  return text.replace(lawRegex, '<span class="law-reference">《$1》第$2条</span>');
}


</script>

<template>
<div class="chat-container">
  <div class="msg-container">
    <div class="msg-item" v-for="msg in messages" :key="msg.timestamp">
      <div class="msg-ai" v-if="msg.sender === 'system'">
       <BaseIcon name="a-Support01"/>
        <span class="text" v-html="formatBotMessage(msg.text)"></span>
      </div>
      <div class="msg-self" v-else>
        <span>
         {{msg.text}}
        </span>
        <BaseIcon name="a-Support01"/>
      </div>
    </div>
    <div class="msg-item" v-if="isLoading">
      <div class="msg-ai">
      <BaseIcon name="a-Support01"/>
      <span>思考中...</span>
      </div>
    </div>
  </div>
  <div class="send-container">
      <textarea class="send-input" v-model="inputMesg"/>
      <button class="send-btn" @click="sendMsg()">发送</button>
  </div>
</div>
</template>

<style scoped>
.chat-container{
  display: flex;
  flex-direction: column;
  height: 80vh;
  max-width: 100%;
  border: 1px solid #a37a7a;
  border-radius: 12px;
}

.msg-ai{
  width: 50%;
  background: #42b883;
  border: 1px saddlebrown;
  border-radius: 12px;
  padding: 10px;
}

.msg-item {
  padding: 10px;
  font-size: 20px;
}

.text {
  font-size: 16px;
  line-height: 1.5;
  padding: 12px 16px;
  border-radius: 18px;
  word-wrap: break-word;
  white-space: pre-wrap;
}


.send-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  width: 100%;
  background: #42b883;
}

.send-input {
  width: 85%;
  height: 80px;
  font-size: 24px;
  border: 2px solid #a37a7a;
  border-radius: 24px;
  outline: none;
}

.msg-self{
  text-align: right;
}

.send-btn {
  height: 80%;
  border-radius: 24px;
  width: 100px;
}



.msg-container {
  flex: 1;
  overflow-y: auto;
}

</style>